package com.wmada.spring.controller;

import com.timerchina.base.ActionResult;
import com.wmada.spring.api.ApiListResult;
import com.wmada.spring.api.ApiResult;
import com.wmada.spring.bean.User;
import com.wmada.spring.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityNotFoundException;
import javax.validation.Valid;
import javax.validation.constraints.Positive;
import javax.validation.constraints.PositiveOrZero;

/**
 * @author will.ma
 * @date 2020-9-28
 */
@RestController
@RequestMapping(value = "/user")
@Validated
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping({"", "/"})
    public ApiListResult<User> getUserList(@PositiveOrZero @RequestParam(name = "page", defaultValue = "0") Integer page,
                                           @Positive @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<User> pageInfo = userService.list(page, pageSize);
        return ApiListResult.restPage(pageInfo);
    }

    @GetMapping("/{id}")
    public ApiResult<User> getUser(@Positive @PathVariable Long id) {
        return ApiResult.success(userService.get(id));
    }

    @PostMapping({"", "/"})
    public ApiResult<User> addUser(@Valid @RequestBody User user) {
        ActionResult<User> result = userService.add(user);
        if (result.isOk()) {
            userService.resetPassword(user, user.getPassword());
            return ApiResult.success(user);
        } else {
            return ApiResult.failure(result.getMessage());
        }
    }

    @PutMapping("/{id}")
    public ApiResult<User> putUser(@PathVariable Long id, @Valid @RequestBody User user) {
        User origin = userService.get(id);

        user.setId(id);
        ActionResult<Void> check = userService.duplicate(user);
        if (check.isFailure()) {
            return ApiResult.failure(check.getMessage());
        }

        origin.setName(user.getName());
        origin.setNickname(user.getNickname());
        origin.setEmail(user.getEmail());
        origin.setPhone(user.getPhone());

        return ApiResult.success(userService.update(origin));
    }

    @DeleteMapping("/{id}")
    public ApiResult<User> deleteUser(@PathVariable Long id) {
        User user = userService.get(id);
        userService.delete(user);
        return ApiResult.success(user);
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(EntityNotFoundException.class)
    public ApiResult<Void> missingUserException() {
        return ApiResult.notFound();
    }

}
